package com.jxdinfo.hussar.example.common.schedulingtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.MdVendorMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.model.MdVendor;
import com.jxdinfo.hussar.example.common.schedulingtask.service.MdVendorService;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.MdVendorVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author QiaoBin
 * @Date 2024/4/02 15:49
 * @Description  md_client供应商表的定时任务
 */
@Component
@AllArgsConstructor
public class MdVendScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(MdVendScheduleTask.class);

    private MdVendorMapper mdVendorMapper;
    private MdVendorService mdVendorService;

//    @Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 0 3 * * ?") // 每天凌晨3点执行
    public void mdVendTask() {
        logger.info("\n用友-供应商表-定时任务-开始执行");
        LocalDateTime nowTime = LocalDateTime.now();
        synchronized ("mdVendTask"){
            logger.info("用友-供应商表-开始查询供应商表中最大的同步时间");
            LocalDateTime scheduleDate = mdVendorMapper.selectMaxScheduleDate();
            String scheduleDateString = "";
            if (scheduleDate != null) {
                scheduleDateString = scheduleDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            //查询创建时间大于定时任务时间，查询出来后把所有数据全部插进去
            logger.info("\n用友-供应商表-开始查询md_vendor表中创建时间大于任务时间的数据,查询参数scheduleDateString={}", scheduleDateString);
            List<MdVendorVO> moreClientList = mdVendorMapper.selectMoreSchedule(scheduleDateString);
            logger.info("\n用友-供应商表-结束查询md_vendor表中创建时间大于任务时间的数据,查询结果moreClientList={}，size={}", moreClientList,moreClientList.size());
            if (moreClientList.size() > 0) {
                ArrayList<MdVendor> mdVendorList = new ArrayList<>();
                for (int i = 0; i < moreClientList.size(); i++) {
                    logger.info("\n用友-供应商表-当前循环次数i={}", i);
                    MdVendorVO mdVendorVO = moreClientList.get(i);
                    MdVendor mdVendor = new MdVendor();
                    mdVendor.setVendorId(mdVendorVO.getVendorId());
                    mdVendor.setVendorCode(mdVendorVO.getVendorCode());     // 编码
                    mdVendor.setVendorName(mdVendorVO.getVendorName());     // 名称
                    mdVendor.setEnableFlag(mdVendorVO.getEnableFlag());     // 是否启用
                    mdVendor.setScheduleTime(nowTime);
                    mdVendor.setCreateBy(mdVendorVO.getCreateBy());
                    mdVendor.setCreateTime(mdVendorVO.getCreateTime());
                    mdVendor.setUpdateBy(mdVendorVO.getUpdateBy());
                    mdVendor.setUpdateTime(mdVendorVO.getUpdateTime());
                    mdVendor.setErpVendId(mdVendorVO.getVendorId());
                    logger.info("\n用友-供应商表-开始向list中存入数据，数据mdVendor={},i={}", mdVendor,i);
                    mdVendorList.add(mdVendor);
                }
                logger.info("\n用友-供应商表-开始向mdVendor表中插入数据，数据mdVendorList={}", mdVendorList);
                boolean b = mdVendorService.saveBatch(mdVendorList, 100);
                logger.info("\n用友-供应商表-结束向mdVendor表中插入数据，插入结果b={}", b);
            }
            if (scheduleDate == null) {
                logger.info("\n用友-供应商表-查询不到任务时间，说明一次也没有同步，之间原封不动的插入就行,也就不需要后续更新");
                return;
            }
            if (scheduleDate != null) {
                logger.info("\n用友-供应商表-开始查询md_vendor表中更新时间大于任务时间，查询参数scheduleDateString={}", scheduleDateString);
                List<MdVendorVO> moreUpdateVendorList = mdVendorMapper.selectUpdateMoreSchedule(scheduleDateString);
                logger.info("\n用友-供应商表-结束查询md_vendor表中更新时间大于任务时间,查询结果moreUpdateClientList={},数量size={}", moreUpdateVendorList, moreUpdateVendorList.size());

                if (moreUpdateVendorList == null || moreUpdateVendorList.size() == 0) {
                    logger.info("\n用友-供应商表-没有查询到更新时间大于任务时间的md_vendor表中数据");
                    return;
                }
                // 转成map集合
                logger.info("\n用友-供应商表-开始把用友表中更新时间大于任务时间的数据转换成主键、对象的map集合");
                Map<Long, MdVendorVO> mdVendorUpdateMap = moreUpdateVendorList.stream().collect(Collectors.toMap(MdVendorVO::getVendorId, t -> t));
                logger.info("\n用友-供应商表-开始获取用友表中更新时间大于任务时间的数据的主键");
                List<Long> vendorIdList = moreUpdateVendorList.stream().map(MdVendorVO::getVendorId).collect(Collectors.toList());
                logger.info("\n用友-供应商表-md_vendor表更新时间大于任务时间的主键集合vendorIdList={},size={}", vendorIdList, vendorIdList.size());

                logger.info("\n用友-供应商表-开始查询md_vendor中erp_vend_id=erp表中主键的数据,参数vendorIdList={}", vendorIdList);
                QueryWrapper<MdVendor> mdVendorueryWrapper = new QueryWrapper<>();
                mdVendorueryWrapper.in("erp_vend_id",vendorIdList);
                mdVendorueryWrapper.eq("deleted_flag",0);
                List<MdVendor> mdVendorUpdateList = mdVendorMapper.selectList(mdVendorueryWrapper);
                logger.info("\n用友-供应商表-结束查询md_vendor中erp_vend_id=erp表中主键的数据,结果mdVendorUpdateList={},size={}", mdVendorUpdateList, mdVendorUpdateList.size());
                if (mdVendorUpdateList.size() > 0) {
                    ArrayList<MdVendor> updateMdVendorList = new ArrayList<>();
                    for (int i = 0; i < mdVendorUpdateList.size(); i++) {
                        logger.info("\n用友-供应商表-当前更新时间大于任务时间，md_vendor表更新，次数i={}", i);
                        MdVendor mdVendor = mdVendorUpdateList.get(i);
                        Long currentMasterId = mdVendor.getErpVendId();
                        mdVendor.setVendorCode(mdVendorUpdateMap.get(currentMasterId).getVendorCode());              // 编码
                        mdVendor.setVendorName(mdVendorUpdateMap.get(currentMasterId).getVendorName());              // 名称
                        mdVendor.setEnableFlag(mdVendorUpdateMap.get(currentMasterId).getEnableFlag());              // 生效状态

                        mdVendor.setScheduleTime(nowTime);
                        mdVendor.setCreateBy(mdVendorUpdateMap.get(currentMasterId).getCreateBy());
                        mdVendor.setCreateTime(mdVendorUpdateMap.get(currentMasterId).getCreateTime());
                        mdVendor.setUpdateBy(mdVendorUpdateMap.get(currentMasterId).getUpdateBy());
                        mdVendor.setUpdateTime(mdVendorUpdateMap.get(currentMasterId).getUpdateTime());
                        logger.info("\n用友-供应商表-向updateMdVendorList存储待要更新的供应商表信息,mdVendor={}", mdVendor);
                        updateMdVendorList.add(mdVendor);
                    }
                    logger.info("\n用友-供应商表-开始更新md_vendor数据,列表updateMdVendorList={}", updateMdVendorList);
                    boolean u = mdVendorService.updateBatchById(updateMdVendorList);
                    logger.info("\n用友-供应商表-结束更md_vendor数据,更新结果u={}", u);
                }
            }
        }
        logger.info("\n用友-供应商表-定时任务-结束执行");
    }
}
